import os
import re
import time
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import Keys
from retrying import retry
from pprint import pprint
from urllib.parse import urljoin
from log import logger


# 设备总览
def summary(driver, web, *args, **kwargs):
    '''
    :param driver:
    :param web:
    :param args:
    :param kwargs:
    :return: 返回设备总数
    '''
    logger.info('设备总览巡检')
    # 拼接url
    url = urljoin(kwargs.get('url'), kwargs.get('path'))
    data = kwargs.get('data')
    file_path = kwargs.get('files')
    # 构造负控单元数据结果
    result = kwargs.get('result')
    logger.info(kwargs)
    driver.get(url)
    locator_of_device_number = "//div[@class='row row3']//div[@class='cardIndicador']//div[@class='num']"
    web.until(EC.visibility_of_element_located((By.XPATH, locator_of_device_number)))
    time.sleep(1)
    pic = os.path.join(file_path, '{}.png'.format('总览'))
    driver.save_screenshot(pic)
    # 获取设备总数
    web_device_total = web.until(
        EC.visibility_of_element_located(
            (By.XPATH,
             "//div[@class='dev-indicador-item'][1]/div[@class='cardIndicador']/div[@class='cardIndicadorRight']/div[@class='num']")))
    device_total = web_device_total.text
    print('设备总数： {}'.format(device_total))
    logger.info('设备总数： {}'.format(device_total))
    return


# 设备管理
@retry(stop_max_attempt_number=3)
def alldevice(driver, web, *args, **kwargs):
    '''
    :param driver:
    :param web:
    :param args:
    :param kwargs:
    :return: 获取不同项目的在线和离线设备的情况
    '''
    print('开始统计设备在线状态....')
    logger.info('开始统计设备在线状态....')

    # 拼接url
    url = urljoin(kwargs.get('url'), kwargs.get('path'))
    data = kwargs.get('data')
    file_path = kwargs.get('files')
    # 构造负控单元数据结果
    result = kwargs.get('result')

    # result = "已并网负控单元在线{}台，离线{}台"
    driver.get(url)

    pprint(kwargs)
    logger.info(kwargs)
    # 设备输入框
    # 设备输入框的xpath 查找规则
    device_search = web.until(EC.visibility_of_element_located((By.XPATH, "//input[@placeholder='请输入搜索内容']")))
    time.sleep(2)

    online = 0
    outline = 0

    # 遍历数组
    for item in data:
        for choice, obj in item.items():
            print('筛选的表头字段为：', choice)
            logger.info('筛选的表头字段为：{}'.format(choice))
            # # 表头选择类型
            # 选择所属产品
            web.until(
                EC.visibility_of_element_located(
                    (By.XPATH, "//thead[@class='has-gutter']//*[contains(text(), '{}')]".format(choice)))).click()
            for type_key, type_value in obj.items():
                print('根据表头字段：{}，所选的类型：{}'.format(choice, type_key))
                logger.info('根据表头字段：{}，所选的类型：{}'.format(choice, type_key))
                # 选择产品类型
                web.until(
                    EC.visibility_of_element_located(
                        (By.XPATH, "//div[@class='el-table-filter']/ul/li[contains(text(), '{}')]".format(type_key))
                    )
                ).click()
                for status, projects in type_value.items():
                    print('{}->{}: 状态: {}'.format(choice, type_key, status))
                    logger.info('{}->{}: 状态: {}'.format(choice, type_key, status))

                    # 选择状态
                    web.until(
                        EC.visibility_of_element_located(
                            (By.XPATH, "//thead[@class='has-gutter']//*[contains(text(), '{}')]".format(
                                status.split(':')[0]))
                        )
                    ).click()

                    # 选择状态类型
                    web.until(
                        EC.visibility_of_element_located(
                            (By.XPATH, "//div[@class='el-table-filter']/ul/li[contains(text(), '{}')]".format(
                                status.split(':')[1]))
                        )
                    ).click()

                    for project in projects:

                        print('当前执行的是：状态:{}的项目:{}'.format(status.split(':')[1], project))
                        logger.info('当前执行的是：状态:{}的项目:{}'.format(status.split(':')[1], project))

                        # 输出产品过滤
                        device_search.clear()
                        device_search.send_keys(project, Keys.ENTER)
                        time.sleep(1)

                        # 获取数量，如果数据为空，则为空
                        try:
                            # 尝试获取设备总数
                            total_str = web.until(EC.presence_of_element_located(
                                (By.XPATH, "//span[@class='el-pagination__total']"))).text
                            # 过滤汉字，只保留数字
                            pattern = '[\u4e00-\u9fa5]{0,}'
                            total_num = int(re.sub(pattern, '', total_str))
                            print('{}状态为{}的设备总数为： {}'.format(project, status.split(':')[1], total_num))
                            logger.info('{}状态为{}的设备总数为： {}'.format(project, status.split(':')[1], total_num))
                            if status.split(':')[1] == '在线':
                                result[project][0] = total_num
                                # online += total_num
                            else:
                                result[project][1] = total_num
                                # outline += total_num
                        except:
                            print('{}状态为{}的设备总数为： {}'.format(project, status.split(':')[1], 0))
                            logger.info('{}状态为{}的设备总数为： {}'.format(project, status.split(':')[1], 0))
                        time.sleep(1)
                        # print(result_data)
                        pic = os.path.join(file_path, '负控-{}-{}.png'.format(project, status.split(':')[1]))
                        driver.save_screenshot(pic)

    # 统计负控单元的在线和离线的总数
    for v in result.values():
        online += v[0]
        outline += v[1]
    pprint(result)
    print(online, outline)
    logger.info(online, outline)
    # return result.format(online, outline)
    return result


@retry(stop_max_attempt_number=3)
def groupdevice(driver, web, *args, **kwargs):
    '''
    :param driver:
    :param web:
    :param args:
    :param kwargs:
    :return: 返回不同地区的设备总数
    '''
    # 拼接url
    url = urljoin(kwargs.get('url'), kwargs.get('path'))
    data = kwargs.get('data')
    file_path = kwargs.get('files')
    result = kwargs.get('result')
    logger.info(kwargs)
    # 下拉展开按钮
    locator_of_expend = "//span[@class='el-tree-node__expand-icon el-icon-caret-right']"
    # 收缩按钮
    locator_of_close = "//span[@class='expanded el-tree-node__expand-icon el-icon-caret-right']"

    # 总数
    locator_of_total_num = "//span[@class='el-pagination__total']"

    driver.get(url)
    print('开始巡检已并网在线设备总量....')
    logger.info('开始巡检已并网在线设备总量....')

    for index, item in enumerate(data):
        for key, value in item.items():
            print('当前巡检的设备地区：', key)
            logger.info('当前巡检的设备地区：{}'.format(key))

            # 找到地区展开
            web.until(EC.visibility_of_all_elements_located((By.XPATH, locator_of_expend)))[index].click()
            # 遍历地区下的项目
            for status, projects in value.items():
                print('当前巡检的动作：', status)
                logger.info('当前巡检的动作：{}'.format(status))
                # 找到运行状态表头
                web.until(
                    EC.visibility_of_element_located((
                        By.XPATH, "//thead[@class='has-gutter']//*[contains(text(), '{}')]".format(status.split(':')[0])
                    ))
                ).click()
                print('点击状态按钮')
                logger.info('点击状态按钮')
                # 筛选状态
                web.until(
                    EC.visibility_of_element_located((
                        By.XPATH,
                        "//div[@class='el-table-filter']/ul/li[contains(text(), '{}')]".format(status.split(':')[1])
                    ))
                ).click()
                print('筛选状态为{}的设备'.format(status.split(':')[1]))
                logger.info('筛选状态为{}的设备'.format(status.split(':')[1]))
                # 遍历项目，每个项目都点击一遍
                for project in projects:
                    print('当前设备所属的项目： ', project)
                    logger.info('当前设备所属的项目： {}'.format(project))

                    web.until(
                        EC.visibility_of_element_located((
                            By.XPATH, "//div[@role='treeitem']//span[contains(@title, '{}')]".format(project)
                        ))
                    ).click()
                    # 暂定一秒
                    time.sleep(1)

                    # 如果抛出异常，说明过滤出的设备总数为空，手动处理该异常
                    try:
                        # 尝试获取设备总数
                        total_str = web.until(EC.presence_of_element_located((By.XPATH, locator_of_total_num))).text
                        # 过滤汉字，只保留数字
                        pattern = '[\u4e00-\u9fa5]{0,}'
                        total_num = int(re.sub(pattern, '', total_str))
                        # print(total_num)
                        print('项目{}: 状态为{}的设备数量：{}'.format(project, status, total_num))
                        logger('项目{}: 状态为{}的设备数量：{}'.format(project, status, total_num))

                        if status.split(':')[1] == '在线':
                            result[key][project][0] = total_num
                            # obj['project']['outline'] += total_num
                            # outline += total_num
                        else:
                            result[key][project][1] = total_num
                            # obj['project']['online'] += total_num
                            # online += total_num
                    except:
                        # print('项目-{}: 状态{}={}'.format(project, status, 0))
                        pass

                    time.sleep(1)
                    pic = os.path.join(file_path, '{}-{}.png'.format(project, status.split(':')[1]))
                    driver.save_screenshot(pic)
                    # driver.save_screenshot("{}:{}.png".format(project, status.split(':')[1]))

            # 找到地区收拢
            web.until(EC.visibility_of_all_elements_located((By.XPATH, locator_of_close)))[-1].click()
            time.sleep(1)

    pprint(result)
    return result
